﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Elasticsearch.Net;
using Microsoft.Extensions.Options;
using Nest;
using StackExchange.Profiling.Internal;
using System.Collections.Immutable;

namespace Abc.Utils;
/// <summary>
/// ES 日志 构造器
/// </summary>
public class EsLoggingProvider : IEsLoggingProvider
{
    public ElasticClient _client;

    public EsLoggingConfigOptions _esLogConfigOptions { get; set; }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="esLogConfigOptions"></param>
    public EsLoggingProvider(IOptionsMonitor<EsLoggingConfigOptions> esLogConfigOptions)
    {
        _esLogConfigOptions = esLogConfigOptions.CurrentValue;
        #region 连接日志
        {
            if (_esLogConfigOptions != null)
            {
                var urls = new StaticConnectionPool(_esLogConfigOptions.Urls?.Select(o => new Uri(o)) ?? new List<Uri>());
                var setting = new ConnectionSettings(urls);
                setting = setting.DefaultIndex(_esLogConfigOptions.DefaultIndex);
                //安全验证
                if (!string.IsNullOrWhiteSpace(_esLogConfigOptions.AuthUserName) && !string.IsNullOrWhiteSpace(_esLogConfigOptions.AuthPassword))
                {
                    setting = setting.BasicAuthentication(_esLogConfigOptions.AuthUserName, _esLogConfigOptions.AuthPassword);
                }
                _client = new ElasticClient(setting);
            }
        }
        #endregion
    }

    /// <summary>
    /// 写日志
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="logContent"></param>
    /// <param name="indexName"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task Write<T>(T logContent, string indexName = "") where T : class, new()
    {
        if (_client == null) throw new Exception("EsLog未初始化");
        //所以名字
        indexName = GetIndexName<T>(indexName);



        ////判断索引是否存在
        //var exists = await IndexExistsAsync(indexName);
        //if (!exists)
        //{
        //    //不存在，创建索引
        //    await _client.CreateIndexAsync<T>(indexName);
        //}

        //索引数据
        var indexResponse = await _client.IndexAsync(logContent,
            s => s.Index(indexName));

        if (!indexResponse.IsValid)
            throw new Exception("新增数据失败:" + indexResponse.OriginalException.Message);
    }

    ///// <summary>
    ///// 索引是否存在
    ///// </summary>
    ///// <param name="index"></param>
    ///// <returns></returns>
    //private async Task<bool> IndexExistsAsync(string index)
    //{
    //    var res = await _client.Indices.ExistsAsync(index);
    //    return res.Exists;
    //}


    /// <summary>
    /// 获取索引名
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="indexName"></param>
    /// <returns></returns>
    private static string GetIndexName<T>(string indexName = "") where T : class
    {
        if (string.IsNullOrWhiteSpace(indexName))
        {
            indexName = indexName.GetIndex<T>().ToLower();
        }
        return indexName.ToLower();
    }

}
